import pygame

class InputHandler:
    def __init__(self, tetris_game):
        self.tetris_game = tetris_game
    
    def handle_events(self):
        """处理所有游戏事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False  # 退出游戏
            elif event.type == pygame.KEYDOWN:
                self.handle_keydown(event.key)
        return True  # 继续游戏
    
    def handle_keydown(self, key):
        """处理键盘按下事件"""
        if self.tetris_game.game_over:
            # 游戏结束时只响应重新开始键
            if key == pygame.K_r:
                self.tetris_game.reset()
        else:
            # 游戏进行中
            if key == pygame.K_p:
                # 暂停/继续游戏
                self.tetris_game.paused = not self.tetris_game.paused
            elif key == pygame.K_r:
                # 重新开始游戏
                self.tetris_game.reset()
            elif not self.tetris_game.paused:
                # 游戏未暂停时处理移动等操作
                if key == pygame.K_LEFT:
                    # 向左移动
                    self.tetris_game.move(-1, 0)
                elif key == pygame.K_RIGHT:
                    # 向右移动
                    self.tetris_game.move(1, 0)
                elif key == pygame.K_DOWN:
                    # 加速下落（软降）
                    self.tetris_game.soft_drop()
                elif key == pygame.K_UP:
                    # 旋转方块
                    self.tetris_game.rotate_piece()
                elif key == pygame.K_SPACE:
                    # 硬降（直接下落到最底部）
                    self.tetris_game.hard_drop()